package com.amqr.mediaplayer.activity;


import android.app.ProgressDialog;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amqr.mediaplayer.R;

/**
 * User: LJM
 * Date&Time: 2017-06-26 & 20:23
 * Describe: Describe Text
 */
public class ScaleAutoPlayVideoActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MEDIA_TEST";
    private TextView mTvPlay, mTvStop, mTvPauseResume;
    private SurfaceView surfaceView;
    private MediaPlayer mediaPlayer;
    private int position;
    private String url1 = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
    //private String url1 = "http://96.9.67.144:81/gchat/8613413422231/1493172571591.mp4";

    private ProgressDialog pd;
    private boolean mIsFullAllScreen;  //是否居中铺满，要么保持原比例
    private boolean mIsAutoPlay;  //是否自动播放


    private boolean mIsLoop;  //是否循环播放
    private boolean mIsVideoSizeKnown;
    private int svFarentWidth;
    private int svFarentHeight;
    private boolean mIsVideoReadyToBePlayed;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scale_auto_video);
        initOther();

        mediaPlayer = new MediaPlayer();

        setFullAllScreen(false);
        setAutoPlay(false);
        setLoop(false);

        surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView);
        // 设置Surface不维护自己的缓冲区，而是等待屏幕的渲染引擎将内容推送到用户面前
        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.d(TAG,"=== addCallback --- surfaceDestroyed");
            }
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Log.d(TAG,"=== addCallback --- surfaceCreated");
                if (position > 0 || mIsAutoPlay) {
                    try {
                        play();// 开始播放
                        mediaPlayer.seekTo(position);// 并直接从指定位置开始播放
                        position = 0;
                    } catch (Exception e) {
                    }
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.d(TAG,"=== addCallback --- surfaceChanged");
            }
        });

        //
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                Log.d(TAG,"=== onPrepared");

                pd.dismiss();

                mIsVideoReadyToBePlayed = true;
                if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
                    if(mIsLoop){
                        mediaPlayer.setLooping(true); // 循环播放  mediaPlayer.setLooping(true);需要写在onPrepared才能生效
                    }
                    Toast.makeText(ScaleAutoPlayVideoActivity.this, "开始播放！", Toast.LENGTH_LONG).show();
                    mediaPlayer.start();
                }
            }
        });


        // 按照谷歌的说法 when the video size is known or updated. 大小已知或者改变时被调用
        mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
            @Override
            public void onVideoSizeChanged(MediaPlayer mediaPlayer, int videoWidth, int videoHeight) {
                Log.d(TAG,"=== onVideoSizeChanged");

                ViewGroup parent = (ViewGroup) surfaceView.getParent();
                svFarentWidth = parent.getWidth();
                svFarentHeight = parent.getHeight();
                if (videoWidth == 0 || videoHeight == 0) {
                    return;
                }

                mIsVideoSizeKnown = true;
                final FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) surfaceView.getLayoutParams();
                if(mIsFullAllScreen){ // 铺满
                    float scaleVideo= videoWidth /(float)videoHeight;
                    float scaleSurface=svFarentWidth/(float)svFarentHeight;
                    if(scaleVideo<scaleSurface){
                        params.width=svFarentWidth;
                        params.height= (int) (svFarentWidth/scaleVideo);
                        params.setMargins(0,(svFarentHeight-params.height)/2,0,(svFarentHeight-params.height)/2);
                    }else{
                        params.height=svFarentHeight;
                        params.width= (int) (svFarentHeight*scaleVideo);
                        params.setMargins((svFarentWidth-params.width)/2,0,(svFarentWidth-params.width)/2,0);
                    }
                }else{ //保持原比例
                    if (videoWidth > svFarentWidth || videoHeight > svFarentHeight) {
                        float scaleVideo = videoWidth / (float) videoHeight;
                        float scaleSurface = svFarentWidth / svFarentHeight;
                        if (scaleVideo > scaleSurface) {
                            params.width = svFarentWidth;
                            params.height = (int) (svFarentWidth / scaleVideo);
                            params.setMargins(0, (svFarentHeight - params.height) / 2, 0, (svFarentHeight - params.height) / 2);
                        } else {
                            params.height = videoHeight;
                            params.width = (int) (svFarentHeight * scaleVideo);
                            params.setMargins((svFarentWidth - params.width) / 2, 0, (svFarentWidth - params.width) / 2, 0);
                        }
                    }

                }
                surfaceView.setLayoutParams(params);
                if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
                    mediaPlayer.start();
                }
            }
        });

        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                Log.d(TAG,"=== onError   ");
                return false;
            }
        });

    }

    @Override
    protected void onPause() {
        // 先判断是否正在播放
        if (mediaPlayer.isPlaying()) {
            // 如果正在播放我们就先保存这个播放位置
            position = mediaPlayer.getCurrentPosition();
            mediaPlayer.stop();
        }
        super.onPause();
    }

    private void play() {
        try {
            pd.show();
            mediaPlayer.reset();
            // setAudioStreamType 在8.0 已经不推荐使用了，但是实测8.0还是可以正常运行的，官方推荐使用 setAudioAttributes(AudioAttributes) 替代
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); //指定流媒体的类型 MediaPlayer设置StreamType需要prepare() or prepareAsync()之前

            Uri uri = Uri.parse(url1);
            mediaPlayer.setDataSource(getApplicationContext(), uri);// 设置需要播放的视频

            mediaPlayer.setDisplay(surfaceView.getHolder());  // 把视频画面输出到SurfaceView
            mediaPlayer.prepareAsync(); // 官方推荐的异步方式进行，异步方式需要在setOnPreparedListener的回到里面手动调用一次 mediaPlayer.start();
            //mediaPlayer.start(); // 播放   当使用 prepareAsync 异步加载资源的方式时，这里的 start()不需要调。 （同步的方式就需要）

        } catch (Exception e) {
        }
    }

    /**
     * 是否铺满（不是完全全屏）
     * 是则铺满，否则保持原比例
     * @param fullAllScreen
     */
    public void setFullAllScreen(boolean fullAllScreen) {
        mIsFullAllScreen = fullAllScreen;
    }

    /**
     * 是否自动播放
     */
    public void setAutoPlay(boolean autoPlay) {
        mIsAutoPlay = autoPlay;
    }

    /**
     * 是否循环播放
     */
    public void setLoop(boolean loop) {
        mIsLoop = loop;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mTvPlay:
                play();
                break;

            case R.id.mTvPauseResume:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                } else {
                    mediaPlayer.start();
                }
                break;

            case R.id.mTvStop:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                break;
            default:
                break;
        }
    }

    private void initOther() {
        pd = new ProgressDialog(this);
        pd.setTitle("请稍后:");
        //设置进度样式
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        mTvPlay = (TextView) this.findViewById(R.id.mTvPlay);
        mTvStop = (TextView) this.findViewById(R.id.mTvStop);
        mTvPauseResume = (TextView) this.findViewById(R.id.mTvPauseResume);
        mTvStop.setOnClickListener(this);
        mTvPlay.setOnClickListener(this);
        mTvPauseResume.setOnClickListener(this);
    }
}
